$(function() {
    userDatatableSource.init();
    pageSource.init();
});

var userDatatable;

/**
 * 表格列定义
 *
 * @type {*[]}
 */
var tableColumns = [{
    field: "id",
    title: "#",
    width: 20,
    textAlign: 'center',
    selector: {
        class: "m-checkbox--solid m-checkbox--brand"
    }},
    {field: "name", title: "用户名称", textAlign: 'center', sortable: false},
    {field: "userid", title: "用户编码", textAlign: 'center', sortable: false}];
/*   {field: "agentcode", title: "关联代理", textAlign: 'center', sortable: false},
   {field: "belongap", title: "所属机场", textAlign: 'center', sortable: false}];*/

/**
 * 初始化表格定义
 */
var userDatatableSource = {
    init: function (){
        userDatatable = $("#user_data").mDatatable(getMDatatableOption("list",{}, tableColumns));
    },
    deleteById: function (ids){
        $.hcPostAjax({
            showLoad: true,
            msgPrefix: '用户删除失败：',
            type:'delete',
            url: basePath + '/wQyUser/'+ids,
            success: function(json) {
                layer.msg('用户删除成功！', {
                    icon: 1,time:1500
                }, function() {
                    userDatatable.reload();
                });
            }
        });
    }
};

var pageSource ={
    init:function(){
        checkEvents();//表单正则校验
        /**
         * 查询
         */
        $("#m_search").on("click", function() {
            var param = {
                name: $.trim($("input[name='name']").val()),
                userid: $.trim($("input[name='userid']").val())
            };
            queryMDatatable(userDatatable, param);
        });

        /**
         * 新增
         */
        $("#m_add").on("click",function(){
            openEditUser('新增用户', null);
        });

        /**
         * 修改数据
         */
        $("#editBtn").on("click",function(){
            var ids = getMDatatableSelectedIds(userDatatable);
            if(ids.length>1){
                layer.msg('只能选中一条数据进行修改！',{icon: 5,anim:6});
                return null;
            }else if(ids.length<1){
                layer.msg('请选中一条数据进行修改！',{icon: 5,anim:6});
                return null;
            }
            var id=ids[0];
            openEditUser('修改用户', id);
        });

        /**
         * 批量删除
         */
        $("#deleteBtn").on("click", function() {
            var ids = getMDatatableSelectedIds(userDatatable);
            if(ids.length === 0) {
                layer.msg('请勾选要删除的用户信息！', {
                    icon: 0
                });
                return;
            }
            var userid = getMDatatableSelectedColumns(userDatatable, "userid");
            layer.confirm('确定批量删除该用户<font color="red">[' + userid + ']</font>？', {
                icon: 3,
                title: '提示',
                btn: ['确定', '取消'] // 按钮
            }, function() {
                userDatatableSource.deleteById(ids.join(','));
            }, function(index) {
                layer.close(index);
            });
        });

        /**
         * 修改密码
         */
        $("#editPasswordBtn").on("click",function(){
            var ids = getMDatatableSelectedIds(userDatatable);
            if(ids.length>1){
                layer.msg('只能选中一条数据进行修改！',{icon: 5,anim:6});
                return null;
            }else if(ids.length<1){
                layer.msg('请选中一条数据进行修改！',{icon: 5,anim:6});
                return null;
            }
            var id=ids[0];
            var names = getMDatatableSelectedColumns(userDatatable, "name");
            openEditPassword('修改密码', id,names);
        });

        /**
         * 重置密码
         */
        $("#resetWord").on('click',function(){
            var ids = getMDatatableSelectedIds(userDatatable);
            if(ids.length>1){
                layer.msg('只能选中一条数据进行重置！',{icon: 5,anim:6});
                return null;
            }else if(ids.length<1){
                layer.msg('请选中一条数据进行重置！',{icon: 5,anim:6});
                return null;
            }
            var id=ids[0];
            var names = getMDatatableSelectedColumns(userDatatable, "name");
            layer.confirm('确定重置该用户<font color="red">[' + names + ']</font>的密码？', {
                icon: 3,
                title: '提示',
                btn:["确认", "取消"]
            }, function(index) {
                $.hcPostAjax({
                    showLoad : true,
                    url :basePath + '/wQyUser/resetWord',
                    data: {
                        id: id
                    },
                    success : function(data) {
                        layer.msg('重置默认密码成功,请用户<font color="red">[' + names + ']</font>重新登入！', {
                            icon : 1,time:1500
                        }, function() {
                            userDatatable.reload();
                            layer.closeAll();
                        });
                    },
                    error : function() {
                        layer.msg('重置失败');
                    }
                });
            })
        });
    }
};

/**
 * 新增和修改
 * @param title
 * @param obj
 */
function openEditUser(title, id) {
    var msg = isEmpty(id) ? "新增" :"编辑";
    layer.open({
        title: title,
        type: 1,
        maxmin: true,
        area: ['60%', '70%'],
        shadeClose: true,
        scrolling:false,
        content: $("#editHtml").html(),
        success: function(layero, index) {
            getAgents();
            if(!isEmpty(id)) {
                renderFormData("#user-form", getDetail(id));
                // 编辑时不让修改密码
                $("#password").attr("disabled","disabled");
                $("#user-form div.password").hide();
                // 编辑时不让修改账号
                $("#userid").attr("disabled","disabled");
            }
            //保存
            $("#edit_yes").on("click", function() {
                if(!isEmpty(id)){
                    $("#password").removeAttr("required").removeAttr("lay-verify").removeAttr("lay-verType");
                }
                form.on('submit(save_user)', function(data) {
                    var param = getFormData("#user-form");
                    param.agentcode=$.trim($("select[name=agentcode]").val());
                    if(!isEmpty(id)){
                        param.id=id;
                    }else{
                        param.password=$.trim($("input[name=password]").val());
                    }
                    $.hcPostAjax({
                        showLoad: true,
                        msgPrefix:msg+ "出错：",
                        url: basePath + '/wQyUser/addOrUpdate',
                        data: param,
                        success: function(data) {
                            layer.msg(msg + '成功！', {
                                icon: 1,time:1500
                            }, function() {
                                userDatatable.reload();
                                layer.closeAll();
                            });
                        }
                    });
                });
            });
            //取消修改
            $("#edit_cancle").on("click", function() {
                layer.closeAll();
            });
        }
    });
}

/**
 * 修改密码
 * @param title
 * @param obj
 */
function openEditPassword(title, id,names) {
    layer.open({
        title: title,
        type: 1,
        maxmin: true,
        area: ['60%', '70%'],
        shadeClose: true,
        scrolling:false,
        content: $("#editPasswordHtml").html(),
        success: function(layero, index) {
            //确认修改
            $("#updateWord").on('click', function() {
                var oldWord = $("#oldWord").val();
                var newWord = $("#newWord").val();
                var confirmWord = $("#confirmWord").val();
                //密码校验
                if (newWord != confirmWord) {
                    layer.msg("新密码与确认密码不一致");
                    return false;
                }
                if (!(/^.*(?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?![.\n])(?!.*\s)^.{8,20}$/.test(oldWord)
                    && /^.*(?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?![.\n])(?!.*\s)^.{8,20}$/.test(newWord)
                    && /^.*(?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?![.\n])(?!.*\s)^.{8,20}$/.test(confirmWord))) {
                    layer.msg("密码最少8位，必须且仅包含大小写字母和数字");
                    return false;
                }
                //保存
                var param = {
                    oldWord: oldWord,
                    newWord: newWord,
                    confirmWord: confirmWord,
                    id: id
                };
                $.hcPostAjax({
                    showLoad : true,
                    url :basePath + '/wQyUser/updateWord',
                    data : param,
                    success : function(data) {
                        layer.msg('密码修改成功,请用户<font color="red">[' + names + ']</font>重新登入！', {
                            icon : 1,time:1500
                        }, function() {
                            userDatatable.reload();
                            layer.closeAll();
                        });
                    },
                    error : function() {
                        layer.msg('更新失败');
                    }
                });
            });
            //取消
            $("#editPassword_cancle").on("click", function() {
                layer.closeAll();
            });
        }
    });
}

/**
 *加载货代
 */
function getAgents() {
    $.ajax({
        async: false,
        type: "post",
        url: basePath + "/hcDicAgent/list",
        data : {
            pagenation : false,
            activestatus: '1'
        },
        success: function (data) {
            var Agents = [];
            for (var i = 0; i < data.data.length; i++) {
                Agents.push({
                    id: data.data[i].agentcode + "",
                    text: data.data[i].agentcode+"/"+data.data[i].namecn
                });
            }
            //选择货代
            $("select[name=agentcode]").val('').select2({
                placeholder: "请选择货代",
                data: Agents,
                multiple:true,
                allowClear: false,
                width: '100%'
            });
        }
    });
}

function getDetail(id) {
    var oldData;
    $.hcPostAjax({
        type:'get',
        url: basePath + "/wQyUser/detail",
        data: {
            id: id
        },
        async: false,
        success: function(data) {
            oldData = data;
        }
    });
    return oldData;
}

function checkEvents() {
    // form 表单校验
    form.verify({
        username: function(value, item){ // value：表单的值、item：表单的DOM对象
            if(!new RegExp("^[a-zA-Z0-9_\u4e00-\u9fa5\\s·]+$").test(value)){
                return '用户名不能有特殊字符';
            }
            if(/(^\_)|(\__)|(\_+$)/.test(value)){
                return '用户名首尾不能出现下划线\'_\'';
            }
            if(/^\d+\d+\d$/.test(value)){
                return '用户名不能全为数字';
            }
        },
        // 我们既支持上述函数式的方式，也支持下述数组的形式
        // 数组的两个值分别代表：[正则匹配、匹配不符时的提示文字]
        /*password: [
            /^[\S]{6,12}$/
            ,'密码必须6到12位，且不能出现空格'
        ]*/
        password: [
            /^.*(?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?![.\n])(?!.*\s)^.{8,20}$/
            , '密码大于8位小于20位，必须包含大小写字母和数字'
        ]
    });
}